<!--
 * @Description: 绑定设备页面
 * @Author: Ronda
 * @Date: 2022-02-16 09:30:08
 * @LastEditors: Ronda
 * @LastEditTime: 2022-05-23 15:08:33
-->
<template>
  <div style="padding: 20px;">
    <!-- 返回按钮 -->
    <el-page-header @back="$router.go(-1)" content="工程页面">
    </el-page-header>

    <!-- 工程信息卡片 -->
    <el-card style="margin-top: 20px;">
      <div slot="header">
        <span style="font-size: 18px; ">工程信息</span>
      </div>
      <!-- 工程基本信息 -->
      <div style="margin-bottom: 20px; line-height: 2.5;">
        <div style="display: flex; margin-bottom: 10px;">
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">工程编号</span>
            <span style="text-align: center; flex: 1;">{{ engObj.serial_number || '暂无' }}</span>
          </div>
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">工程名称</span>
            <span style="text-align: center; flex: 1;">{{ engObj.name || '暂无' }}</span>
          </div>
        </div>

        <div style="display: flex; margin-bottom: 10px;">
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">工程类型</span>
            <span style="text-align: center; flex: 1;">{{ engObj.type || '暂无' }}</span>
          </div>
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">工程状态</span>
            <span style="text-align: center; flex: 1;">{{ engObj.status || '暂无' }}</span>
          </div>
        </div>

        <div style="display: flex; margin-bottom: 10px;">
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">开始时间</span>
            <span style="text-align: center; flex: 1;">{{ engObj.create_time | fmtDate }}</span>
          </div>
          <div style="width: 100%; display: flex; align-items: center;">
            <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">结束时间</span>
            <span style="text-align: center; flex: 1;">{{ engObj.end_time ? moment(engObj.end_time).format('YYYY-MM-DD')
              : '暂无' }}</span>
          </div>
        </div>

        <div style="display: flex; margin-bottom: 10px; align-items: center;">
          <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">地址</span>
          <span style="text-align: center; flex: 1;">{{ engObj.address || '暂无' }}</span>
        </div>

        <div style="display: flex; margin-bottom: 10px; align-items: center;">
          <span style="font-weight: bold; min-width: 80px;font-size: large;color: #565656;">工程负责人</span>
          <span style="text-align: center; flex: 1;">{{ engObj.charge_id || '暂无' }}</span>
        </div>
      </div>
    </el-card>

    <!-- 设备绑定区域 -->
    <el-card style="margin-top: 20px;">
      <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
        <span style="font-size: 18px; ">绑定信息</span>
        <el-button type="primary" @click="toBind">绑定</el-button>
      </div>

      <div>
        <!-- 设备列表 -->
        <el-table :data="deviceList" style="width: 100%; margin-top: 5px;" @selection-change="handleSelectionChange"
          :border="false">
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="serial_number" label="设备编号" width="150" align="center"></el-table-column>
          <el-table-column prop="name" label="设备名称" width="150" align="center"></el-table-column>
          <el-table-column prop="longitude" label="经度" width="120" align="center"></el-table-column>
          <el-table-column prop="latitude" label="纬度" width="120" align="center"></el-table-column>
          <el-table-column prop="video" label="视频地址" width="200" align="center">

          </el-table-column>
          <el-table-column prop="online_status" label="在线状态" width="100" align="center">
            <template v-slot="scope">
              <el-tag :type="scope.row.online_status ? 'success' : 'danger'">
                {{ scope.row.online_status ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template v-slot="scope">
              <el-link :disabled="scope.row.status == '已结束' ? true : false" style="font-size: 12px;" :underline="false"
                type="primary" @click="unbindDevice(scope.row)">解绑</el-link>
              <el-link v-if="!scope.row.online_status" :disabled="scope.row.status == '已结束'"
                style="margin-left: 5px; font-size: 12px;" :underline="false" type="success"
                @click="onlineDevice(scope.row)">上线</el-link>
              <el-link v-else :disabled="scope.row.status == '已结束'" style="margin-left: 5px; font-size: 12px;"
                :underline="false" type="danger" @click="closeDevice(scope.row)">下线</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 绑定设备抽屉 -->
    <el-drawer title="绑定设备" :visible.sync="showBindDrawer" direction="rtl" size="50%"
      :before-close="handleBindDrawerClose">
      <div style="padding: 20px;">
        <div style="margin-bottom: 20px;">
          <h3 style="margin-bottom: 15px;">1. 选择设备</h3>
          <el-form :model="{ selectedDeviceId, ...deviceForm }" :rules="rules" ref="bindForm" label-width="80px">
            <el-form-item label="设备" prop="selectedDeviceId">
              <el-select v-model="selectedDeviceId" filterable placeholder="请选择设备" style="width: 100%"
                @change="handleDeviceChange">
                <el-option v-for="item in availableDevices" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div style="margin-bottom: 20px;">
          <h3 style="margin-bottom: 15px;">2. 配置设备</h3>
          <el-form :model="{ selectedDeviceId, ...deviceForm }" :rules="rules" ref="bindForm" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="deviceForm.longitude" placeholder="请输入经度"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="deviceForm.latitude" placeholder="请输入纬度"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="视频流" prop="video">
              <el-input v-model="deviceForm.video" placeholder="请输入视频流地址"></el-input>
            </el-form-item>
          </el-form>
        </div>

        <div class="demo-drawer__footer">
          <el-button @click="showBindDrawer = false">取消</el-button>
          <el-button type="primary" @click="submitBindForm">绑定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import moment from 'moment';
import { get } from '@/utils/request';

export default {
  data() {
    return {
      engObj: {},
      manager: {},
      deviceList: [],
      selectedDevices: [],
      showBindDrawer: false,
      availableDevices: [], // 可绑定的设备列表
      selectedDeviceId: null, // 选中的设备ID
      deviceForm: {
        longitude: '',
        latitude: '',
        video: ''
      },
      rules: {
        selectedDeviceId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' }
        ],
        video: [
          { required: true, message: '请输入视频地址', trigger: 'blur' }
        ]
      }
    }
  },
  filters: {
    fmtDate(value) {
      return value ? moment(value).format('YYYY-MM-DD') : '暂无';
    }
  },
  created() {
    this.engObj = this.$route.query;
    this.loadManager();
    this.loadDevices();
    this.bindService();
  },

  methods: {
    //去绑定
    toBind(){
      this.showBindDrawer = true;
      this.bindService()
    },
    moment,
    //关闭抽屉清空表单校验结果
    close() {
      this.$refs['myForm'].resetFields();
    },
    submitBindForm() {
      this.$refs.bindForm.validate(valid => {
        if (valid) {
          this.confirmBindService();
        } else {
          this.$message.warning('请填写完整信息');
          return false;
        }
      });
    },
    // 设备选择变化
    handleDeviceChange(deviceId) {
      this.selectedDeviceId = deviceId;
      const device = this.availableDevices.find(item => item.id === deviceId);
      if (device) {
        this.deviceForm = {
          longitude: device.longitude || '',
          latitude: device.latitude || '',
          video: device.video || ''
        };
      }
      // 手动触发验证
      this.$nextTick(() => {
        this.$refs.bindForm.validateField('selectedDeviceId');
      });
    },





    // 查询可绑定的设备
    async bindService() {
      try {
        // 获取所有未绑定设备
        const unbindDevicesRes = await get('/device/pageQuery', {
          page: 1,
          pageSize: 1000,
          bind_status: 0  // 只查询未绑定设备
        });
        // 获取当前工程已绑定的设备ID列表
        const currentProjectDevicesRes = await get('/device/pageQuery', {
          page: 1,
          pageSize: 1000,
          engineer_id: this.engObj.id
        });
        const boundDeviceIds = currentProjectDevicesRes.data?.list?.map(d => d.id) || [];
        // 过滤掉已绑定的设备
        this.availableDevices = (unbindDevicesRes.data?.list || []).filter(
          device => !boundDeviceIds.includes(device.id)
        );
      } catch (error) {
        console.error('获取可绑定设备失败:', error);
        this.availableDevices = [];
        this.$message.error('获取可绑定设备失败');
      }
    },

    // 确认绑定设备
    async confirmBindService() {
      if (!this.selectedDeviceId) {
        this.$message.warning('请选择要绑定的设备');
        return;
      }

      try {
        //使用get方法，参数通过查询字符串传递
        await get('/engineer/bindService', {
          engineer_id: this.engObj.id,
          device_id: this.selectedDeviceId,
          longitude: this.deviceForm.longitude,
          latitude: this.deviceForm.latitude,
          video: this.deviceForm.video,
          online_status: 0
        });

        this.$message.success('设备绑定成功');
        this.showBindDrawer = false;
        this.loadDevices(); // 重新加载设备列表
        this.bindService();  // 重新加载可绑定设备列表
      } catch (error) {
        console.error('绑定设备失败:', error);
        this.$message.error('绑定设备失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 关闭绑定抽屉
    handleBindDrawerClose(done) {
      this.selectedDeviceId = null;
      this.deviceForm = {
        longitude: '',
        latitude: '',
        video: ''
      };
      done();
    },

    // 加载区域经理信息
    async loadManager() {
      if (this.engObj.charge_id) {
        try {
          const res = await get('/engineer/findEngineerDeviceTree', {
            id: this.engObj.charge_id
          });
          this.manager = res.data || {};
        } catch (error) {
          console.error('加载负责人信息失败:', error);
          this.manager = {};
        }
      }
    },

    // 加载设备列表
    async loadDevices() {
      try {
        const res = await get('/device/pageQuery', {
          page: 1,
          pageSize: 10,
          engineer_id: this.engObj.id // 获取当前工程绑定的设备
        });
        this.deviceList = res.data?.list || [];
      } catch (error) {
        console.error('加载设备列表失败:', error);
        this.deviceList = [];
      }
    },

    // 处理选择设备
    handleSelectionChange(val) {
      this.selectedDevices = val;
    },

    // 解绑设备
    async unbindDevice(device) {
      this.$confirm('此操作将解绑该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await get('/engineer/unbindDevice', {
            engineer_id: this.engObj.id,
            device_id: device.id
          });
          this.$message.success('设备解绑成功');
          this.loadDevices();
        } catch (error) {
          console.error('解绑设备失败:', error);
          this.$message.error('解绑设备失败');
        }
      }).catch(() => {
        this.$message.info('已取消解绑');
      });
    },

    //上线设备
    async onlineDevice(device) {
      this.$confirm('此操作将使设备上线, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await get('/device/openDevice', {
            id: device.id
          });
          this.$message.success('设备已上线');
          this.loadDevices(); // 刷新设备列表
        } catch (error) {
          console.error('上线设备失败:', error);
          this.$message.error('上线设备失败: ' + (error.response?.data?.message || error.message));
        }
      }).catch(() => {
        this.$message.info('已取消上线');
      });
    },

    // 下线设备
    async closeDevice(device) {
      this.$confirm('此操作将使设备下线, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await get('/device/closeDevice', {
            id: device.id
          });
          this.$message.success('设备已下线');
          this.loadDevices();
        } catch (error) {
          console.error('下线设备失败:', error);
          this.$message.error('下线设备失败');
        }
      }).catch(() => {
        this.$message.info('已取消下线');
      });
    }
  }
}
</script>

<style scoped>
.el-divider {
  margin: 20px 0;
}

.demo-drawer__footer {
  border-top: 1px solid #ededed;
  padding-top: 10px;
  position: fixed;
  bottom: 50px;
  width: 50%;
  text-align: center;
}
</style>